import React, { Fragment } from 'react'
import { View, StatusBar, StyleSheet, Image } from 'react-native'
import PropTypes from 'prop-types'
import Orientation from 'react-native-orientation-locker'
import { ScaleS, HEIGHT, WIDTH, STATUSBAR_HEIGHT, IS_IOS, IS_ANDROID } from 'src/utils/ScreenUtil'
import CustomButton from 'src/components/button/CustomButton'
import { PolyvVodPlayer, RNTPolyvVodManager } from 'src/bridge/index'
import PolyvVodConfig from 'src/bridge/PolyvVodConfigModule'
import PolyvVodPlayerComponent from 'src/bridge/PolyvVodPlayerModule'
import NavigationUtil from 'src/utils/NavigationUtil'

const TAG = 'PolyvVodView'
export default class PolyvVodView extends React.PureComponent {
  render () {
    const { goBack, style, children, showControl, loopPlay, isCanDrag } = this.props
    return (
      IS_IOS ? (
        <PolyvVodPlayer
          style={StyleSheet.absoluteFillObject}
          ref={this.setPolyvVodPlayerRef}
          onPlayVodEvent={this._onPlayVodEvent}
        />
      ) : (
        <PolyvVodPlayerComponent
          style={style}
          ref={this.setPolyvVodPlayerRef}
          showControl={showControl}
          loopPlay={loopPlay}
          isCanDrag={isCanDrag}
          onPlayVodEvent={this._onPlayVodEvent}
        />
      )

    )
  }

  componentDidMount () {
    this._configOrientations()
    this._subscriptNavigation()
  }

  _subscriptNavigation = () => {
    const navigation = NavigationUtil.getNavigation()
    this.willFocusSubscription = navigation.addListener(
      'willFocus',
      this.componentWillFocus
    )
    this.didFocusSubscription = navigation.addListener(
      'didFocus',
      this.componentDidFocus
    )
  }

  componentWillFocus () {
    console.info('componentWillFocus')
  }

  componentDidFocus () {
    console.info('componentDidFocus')
  }

  componentWillUnmount () {
    console.info(TAG, 'componentWillUnmount')
    this._freeOrientations()
    this._freePlayer()
  }

  setOrientationListener = (enable) => {
    if (IS_ANDROID) {
      if (this.polyvVodPlayerRef) {
        this.polyvVodPlayerRef.orientationListener(enable)
      }
    }
  }

  setFullScreen = (fullScreen) => {
    if (IS_ANDROID) {
      if (this.polyvVodPlayerRef) {
        this.polyvVodPlayerRef.setFullScreen(fullScreen)
      }
    }
  }

  setNativeProps (nativeProps) {
    this.polyvVodPlayerRef.setNativeProps(nativeProps)
  }

  _configOrientations = () => {
    if (IS_IOS) {
      Orientation.lockToPortrait()
      Orientation.addOrientationListener(this._onOrientationDidChange)
    }
  }

  _freeOrientations = () => {
    if (IS_IOS) {
      Orientation.lockToPortrait()
      Orientation.removeOrientationListener(this._onOrientationDidChange)
    }
  }

  _onOrientationDidChange = orientation => {
    console.log(TAG, '_onOrientationDidChange', orientation)
    // LayoutAnimation.easeInEaseOut()
    // if (orientation === 'LANDSCAPE-LEFT' || orientation === 'LANDSCAPE-RIGHT') {
    //   this.props.polyVodSkinPropsChange('fullscreen', true)
    // } else {
    //   this.props.polyVodSkinPropsChange('fullscreen', false)
    // }
  }

  setPolyvVodNativeProps = (key, value) => {
    console.log(TAG, 'setPolyvVodNativeProps', key, value)
    if (key === 'paused') {
      if (value) {
        // 暂停
        if (IS_IOS) {
          RNTPolyvVodManager.pause()
        } else {
          this.pause()
        }
      } else {
        if (IS_IOS) {
          RNTPolyvVodManager.play()
          console.log('unlockAllOrientations')
          Orientation.unlockAllOrientations()
        } else {
          console.log(TAG, 'paused', value)
          this.initPlay()
        }
      }
    }
    // this.polyvVodPlayerRef.setNativeProps({
    //   [key]: value
    // })
  }

  setPolyvVodPlayerRef = ref => (this.polyvVodPlayerRef = ref)

  updateVid = (vid) => {
    this.polyvVodPlayerRef.updateVid(vid)
  }

  initPlay = () => {
    this.polyvVodPlayerRef.initPLay()
  }

  play () {
    this.polyvVodPlayerRef.play()
  }

  pause () {
    this.polyvVodPlayerRef.pause()
  }

  release = () => {
    this.polyvVodPlayerRef.release()
  }

  configPolyVodPlayer = ({
    polyvSetting: {
      userId,
      appId,
      appSecret,
      sdkString: vodKey,
      encryptionKey: decodeKey,
      encryptionVector: decodeIv
    },
    channel: { demandUrl: vid, no: channelId, vidWarmVideo }
  }, type, callback) => {
    const User = {
      // 初始化所需的数据
      viewerId: 'rn_viewerId',
      nickName: 'rn_nickName'
    }
    if (IS_IOS) {
      RNTPolyvVodManager.initPolyVod(
        vodKey,
        decodeKey,
        decodeIv,
        User.viewerId,
        User.nickName
      )
        .then(ret => {
          if (ret.code !== 0) {
            // 初始化失败
            var str =
              '初始化失败  errCode=' + ret.code + '  errMsg=' + ret.message
            console.log(str)
          } else {
            // 初始化成功
            console.log('初始化成功')
            RNTPolyvVodManager.updateVid(vid)
          }
        })
        .catch(error => {
          console.log('初始化error', error)
        })
    } else {
      PolyvVodConfig.initPolyVod(
        vodKey,
        decodeKey,
        decodeIv,
        User.viewerId,
        User.nickName
      )
        .then(ret => {
          if (ret.code !== 0) {
            // 初始化失败
            var str =
              '初始化失败  errCode=' + ret.code + '  errMsg=' + ret.message
            console.log(str)
          } else {
            // 初始化成功
            console.log('初始化成功')
            if (type === 'warm') {
              this.polyvVodPlayerRef.updateVid(vidWarmVideo)
              // this.polyvVodPlayerRef.initPlay()
            } else {
              this.polyvVodPlayerRef.updateVid(vid)
              // this.polyvVodPlayerRef.initPlay()
            }
            callback && callback()
          }
        })
        .catch(error => {
          console.log('初始化error', error)
        })
    }
  }

  _freePlayer = () => {
    if (IS_IOS) {
      RNTPolyvVodManager.freePlayer()
    } else {
      // this.polyvVodPlayerRef.freePlayer()
      this.polyvVodPlayerRef.release()
    }
  }

  _onPlayVodEvent = data => {
    console.log('_onPlayVodEvent', data.nativeEvent)
    const { key, value } = data.nativeEvent
    if (key === 'goBack') {
      const { goBack } = this.props
      goBack && goBack()
    } else {
      if (key === 'paused') {
        // 打开旋转屏幕
        if (!value) {

        }
        return
      }
      if (IS_ANDROID) {
        // this.props.polyVodSkinPropsChange(key, value)
        if (key === 'fullscreen') {
          // StatusBar.setTranslucent(true)
          if (value) {
            StatusBar.setHidden(true)
          }
        }
        this.props.polyVodSkinPropsChange(key, value)
      } else {
        this.props.polyVodSkinPropsChange(key, value)
      }
    }
  }
}

PolyvVodView.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  children: PropTypes.node,
  company: PropTypes.object,
  channel: PropTypes.object,
  polyVodState: PropTypes.object,
  polyVodSkinPropsChange: PropTypes.func,
  goBack: PropTypes.func
}
const styles = StyleSheet.create({
  statusbar: {
    width: WIDTH,
    height: STATUSBAR_HEIGHT,
    backgroundColor: 'black'
  },
  backBtn: {
    position: 'absolute',
    zIndex: 1000,
    top: STATUSBAR_HEIGHT,
    left: 0,
    width: 59,
    height: 53,
    justifyContent: 'center',
    alignItems: 'center'
  },
  flex1: {
    flex: 1
  }
})
